<template>
  <div class="menu-management">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <div class="search-bar">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索菜单名称或URL"
          :prefix-icon="Search"
          clearable
          style="width: 300px"
          @keyup.enter="handleSearch"
        />
        <el-button 
          type="primary" 
          :icon="Search" 
          @click="handleSearch"
          :loading="tableLoading"
        >
          搜索
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <div class="action-buttons">
        <el-button 
          type="primary" 
          :icon="Plus" 
          v-if="userStore.hasPermission('menu.create')"
          @click="handleAdd"
        >
          新增菜单
        </el-button>
        <el-button 
          type="danger" 
          :icon="Delete"
          :disabled="!multipleSelection.length"
          v-if="userStore.hasPermission('menu.delete')"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="tableLoading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 菜单表格 -->
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="menuName" label="菜单名称" min-width="150" />
      <el-table-column prop="menuUrl" label="菜单URL" min-width="200" />
      <el-table-column prop="parentId" label="父菜单ID" width="100" />
      <el-table-column prop="menuOrder" label="排序" width="80" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            :disabled="row.isSystem"
            v-if="userStore.hasPermission('menu.update')"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            :disabled="row.isSystem"
            v-if="userStore.hasPermission('menu.delete')"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑菜单' : '新增菜单'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="menuForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <el-input 
            v-model="formData.menuName" 
            placeholder="请输入菜单名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="菜单URL" prop="menuUrl">
          <el-input 
            v-model="formData.menuUrl" 
            placeholder="请输入菜单URL"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="父菜单ID" prop="parentId">
          <el-input-number 
            v-model="formData.parentId" 
            :min="0"
            placeholder="0表示顶级菜单"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="menuOrder">
          <el-input-number 
            v-model="formData.menuOrder" 
            :min="0"
            placeholder="数字越小排序越靠前"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="submitLoading"
          >
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  Search, 
  Plus, 
  Delete, 
  Edit, 
  Refresh 
} from '@element-plus/icons-vue'

// 响应式数据
const userStore = useUserStore()
const tableLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const tableData = ref([])
const multipleSelection = ref([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10
})

// 表单数据
const formData = ref({
  menuName: '',
  menuUrl: '',
  parentId: 0,
  menuOrder: 0
})

// 表单验证规则
const formRules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  menuUrl: [
    { required: true, message: '请输入菜单URL', trigger: 'blur' },
    { max: 200, message: 'URL长度不能超过 200 个字符', trigger: 'blur' }
  ],
  parentId: [
    { type: 'number', message: '父菜单ID必须是数字', trigger: 'blur' }
  ],
  menuOrder: [
    { type: 'number', message: '排序必须是数字', trigger: 'blur' }
  ]
}

// 表单引用
const menuForm = ref()

// 数据加载
const loadTableData = async () => {
  tableLoading.value = true
  try {
    // 使用真实的菜单分页API
    const { menuApi } = await import('@/api/menu')
    const response = await menuApi.getMenusPaged(
      (queryParams.page - 1), 
      queryParams.pageSize,
      searchForm.keyword ? { keyword: searchForm.keyword } : {}
    )
    
    console.log('菜单列表API返回数据:', response)
    
    if (response.data && response.data.menus) {
      // 将真实菜单数据转换为表格需要的格式
      tableData.value = response.data.menus.map(menu => ({
        id: menu.id,
        menuName: menu.menuName,
        menuUrl: menu.menuUrl,
        parentId: menu.parentId || 0,
        menuOrder: menu.menuOrder || 0,
        createdAt: menu.createdAt ? new Date(menu.createdAt).toLocaleString() : '-'
      }))
      
      total.value = response.data.totalCount || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载菜单列表失败:', error)
    ElMessage.error('加载菜单列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  loadTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  queryParams.page = 1
  loadTableData()
}

// 刷新
const handleRefresh = () => {
  loadTableData()
}

// 分页处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.page = 1
  loadTableData()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  loadTableData()
}

// 多选处理
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 新增菜单
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    menuName: '',
    menuUrl: '',
    parentId: 0,
    menuOrder: 0
  }
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = {
    id: row.id,
    menuName: row.menuName,
    menuUrl: row.menuUrl,
    parentId: row.parentId,
    menuOrder: row.menuOrder
  }
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${row.menuName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('删除功能待实现')
    // TODO: 实现删除API调用
    // await menuApi.deleteMenu(row.id)
    // ElMessage.success('菜单删除成功')
    // loadTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const ids = multipleSelection.value.map(item => item.id)
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${ids.length} 个菜单吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('批量删除功能待实现')
    // TODO: 实现批量删除API调用
    // await menuApi.batchDeleteMenus(ids)
    // ElMessage.success('菜单批量删除成功')
    // loadTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除菜单失败:', error)
      ElMessage.error('批量删除菜单失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  const form = menuForm.value
  if (!form) return
  
  try {
    await form.validate()
    submitLoading.value = true
    
    // 使用真实的菜单API提交数据
    const { menuApi } = await import('@/api/menu')
    const menuData = {
      menuName: formData.value.menuName,
      menuUrl: formData.value.menuUrl,
      parentId: formData.value.parentId || 0,
      menuOrder: formData.value.menuOrder || 0
    }
    
    if (isEdit.value && formData.value.id) {
      // 更新菜单 (如果有更新API的话)
      console.log('更新菜单:', menuData)
      ElMessage.success('菜单更新功能待实现')
    } else {
      // 创建新菜单
      await menuApi.createMenu(menuData)
      ElMessage.success('菜单创建成功')
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('菜单操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar,
  .action-buttons {
    justify-content: center;
  }
}
</style>
